package com.wk.constains.net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import com.wk.job.Job;

public class SendUtils {
	private static Socket  client = null;
	private  static String SUCESS = "SUCESS";
	private static final int TRYTIMES = 5; 
	static {
		System.out.println("任务分发！！！");		
	}
	
	//获取一次连接发送一个对象
	public static boolean sendJob(String ip,int port, Job job){
		ObjectOutputStream objob =null;
		DataInputStream dataInputStream=null;
		String status =null;
		
		try {
			int count =0;
			while(count<TRYTIMES && client ==null){
				client = new Socket(ip, port);
				if(client == null ){
					System.out.println("失败重试"+count+" 次，共尝试"+TRYTIMES+"次");
					try {
						Thread.sleep(1000L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}	
			}
			if(client == null){
				return false;
			}
			objob = new ObjectOutputStream(client.getOutputStream());
			objob.writeObject(job);
			objob.flush();
			
			dataInputStream = new DataInputStream(client.getInputStream());
			status = dataInputStream.readUTF();
			System.out.println(status+" -> "+job.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				objob.close();
				dataInputStream.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(SUCESS.equals(status)){
			return true;
		}
		return false;
	}
	
	/**
	 * 报告job完成
	 * @param ip
	 * @param port
	 * @param job
	 * @return
	 */
	public static boolean sendMessage(String ip,int port, Job job){
		
		DataOutputStream output = null;
		String status =null;
		try {
			System.out.println("获取连接！");
			client = new Socket(ip, port);
			System.out.println("开始发送...");
			if(client == null ){
				return false;
			}
			output = new DataOutputStream(client.getOutputStream());
			output.writeBoolean(true);
			output.flush();
			output.writeUTF(job.getId());
			output.flush();
			output.writeDouble(job.getJobInfo());
			output.flush();
			System.out.println("发送成功 -> "+job.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				output.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(SUCESS.equals(status)){
			return true;
		}
		return false;
	}
	
	
}
